package pers.vic.boot.console.system.controller;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import pers.vic.boot.base.controller.BaseController;
import pers.vic.boot.base.model.BaseResponse;
import pers.vic.boot.console.system.model.SysUser;
import pers.vic.boot.console.system.service.SysUserService;
import pers.vic.boot.security.jwt.AuthorityInfo;
import pers.vic.boot.security.jwt.JwtUtil;
import pers.vic.boot.util.encrypt.PasswordUtils;

/** 
 * @description: 系统用户控制层
 * @author: Vic.xu
 * @date: 2019年11月18日 下午2:12:59
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController<SysUserService, SysUser>{

	/**
	 * 判断用户名是否重复
	 */
	@PostMapping(value = "/check", params = {"username"})
	public BaseResponse checkUsername(Integer id, String username) {
		return BaseResponse.success(service.checkUsername(id, username));
	}
	
	/**
	 * 保存
	 * @param entity
	 * @return
	 */
	@PostMapping(value = "/save", params = {"roleIds"})
	public BaseResponse save(SysUser entity, @RequestParam(required = false)Integer[] roleIds) {
		service.save(entity, roleIds);
		return BaseResponse.success(entity);
	}
	
	
	/**
	 * @description: 修改密码
	 * @author: Vic.xu
	 * @date: 2020年2月17日 下午4:15:27
	 * @return
	 */
	@PostMapping(value = "/password")
	@RequiresAuthentication
	public BaseResponse password(String oldPassword, String password) {
		AuthorityInfo userInfo =  JwtUtil.getAuthorityInfoFromShiro();
		Integer id = userInfo.getUserId();
		SysUser user = service.findById(id);
		if(user == null) {
			return BaseResponse.error("不存在的用户");
		}
		if(!PasswordUtils.validatePassword(oldPassword, user.getPassword())) {
			return BaseResponse.error("密码错误"); 
		}
		user.setPassword(PasswordUtils.entryptPassword(password));
		service.save(user);
		return BaseResponse.success();
	}
	
	
}
